//require jquery_1.7.2 swfobject.js
//external videoURL,height,width
$(document).ready(function(){
	
	tampering(function(videoURL,height,width){
		var flashvars = {
			src: escape(videoURL),
			plugin_m3u8: chrome.extension.getURL("dist/HLSProviderOSMF.swf")
		};

		var params = {
			allowFullScreen: true,
			allowScriptAccess: "always",
			bgcolor: "#000000"
		};
		var attrs = {
			name: "AdsFreePlayer"
		};

		swfobject.embedSWF(
			chrome.extension.getURL("dist/StrobeMediaPlayback.swf"),
			"AdsFreePlayer",
			width,height,
			"10.2",
			null,flashvars,params,attrs
		);
	});
	
	
});


var qualities = {
	"flv":0,
	"mp4":1,
	"hd2":2,
	"hd3":3
}

var idExtractor = /http[s]?:\/\/v\.youku\.com\/.*\/id_([A-Za-z0-9]{13})\.html/

var videoSites = {
	"youku":{
		detect: function(){
			var regex = /http[s]?:\/\/static\.youku\.com\/v[0-9.]+\/v\/swf\/player_[a-z]+\.swf/
			return jQuery("#movie_player").length > 0 && regex.test(jQuery("#movie_player").attr("data"))
		},
		inject: function(){
			jQuery(".playArea").children().remove()
			jQuery(".playArea").append("<div id='AdsFreePlayer' ></div>")
		},
		extractInfo : function(callback){
			var parts = window.location.href.match(idExtractor)
			if(parts.length <2) {
				console.error("Cannot get video ID")
				return;
			}
			var id = parts[1]
			var height = 496
			var width = 640
			jQuery.ajax({
				url:"/player/getPlaylist/VideoIDS/"+id,
				success:function(res){
				var data = JSON.parse(res)
				if(data.data && data.data.length > 0 ){
					var orderedTypes = data.data[0].streamtypes.sort(function(a,b){return (qualities[a]?qualities[a]:0)-(qualities[b]?qualities[b]:0);})
					var type = orderedTypes.pop()
					callback(
						"http://v.youku.com/player/getM3U8/vid/"+id+"/type/"+type+"/video.m3u8",
						height,
						width
					)
				}else{
					console.log("error! get video info failed, api returns: ")
					console.log(data)
				}
				}
			});
			
		}
	}
}
/*
callback: function(videoURL,height,width)
*/
function tampering(callback){

	for(var site in videoSites){
		console.log("checking.."+site)
		var siteFuncs = videoSites[site]
		if(siteFuncs.detect()){
			siteFuncs.inject();
			siteFuncs.extractInfo(callback)
			break;
		}
	}

}